<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS-如何在JSON树形结构中找到子节点的父级路径</title>
  <script>
    const data = [{
      id: 11,
      pid: 'a1',
      text: 11,
      children: [{
        id: 21,
        pid: 'b1',
        text: 21,
        children: [{
          id: 31,
          pid: 'c1',
          text: 31,
          children: [{
            id: 41,
            pid: 'd1',
            text: 41,
            children: []
          },
          {
            id: 42,
            pid: 'd2',
            text: 42,
            children: []
          }
          ]
        },
        {
          id: 32,
          pid: 'c2',
          text: 32,
          children: []
        }
        ]
      },
      {
        id: 22,
        pid: 'b2',
        text: 22,
        children: []
      }
      ]
    },
    {
      id: 12,
      pid: 'a2',
      text: 12,
      children: []
    }
    ]

    /**
     * 查找节点, 返回数据深度
     */
    function findIndexArray(data, id, indexArray) {
      let arr = Array.from(indexArray)
      for (let i = 0, len = data.length; i < len; i++) {
        arr.push(data[i].pid)
        if (data[i].id === id) {
          return arr
        }
        let children = data[i].children
        if (children && children.length) {
          let result = findIndexArray(children, id, arr)
          if (result) return result
        }
        arr.pop()
      }
      return false
    }

    console.log(findIndexArray(data, 42, [])) // ["a1", "b1", "c1", "d2"]
    // findIndexArray(data, 21, [])
    // console.log(data)
  </script>
</head>

<body>

</body>

</html>